/**
 * @file 大屏配置
 * @date 2020-05-15
 */

import React, {Component, Fragment} from 'react';
import {withRouter} from 'react-router-dom';
import {Form} from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
    Select,
    Radio,
    message,
    Button,
    Input,
    DatePicker,
    InputNumber,
    Spin,
    Popconfirm,
} from 'antd';
import debounce from 'lodash/debounce';
import moment from 'moment';
import DataDetail from '~/component/DataDetail';
import {createScreen, updateScreen, getAccountList, getScreenDetail} from '~/service/screen';
import {PAGE_ENUM} from '~/utils/menu';

const {TextArea} = Input;
const {RangePicker} = DatePicker;
const {Option} = Select;

class MoneyScreenConfig extends Component {
    static propTypes = {
    };

    constructor(props) {
        super(props);
        this.handleSearch = debounce(this.handleSearch, 0);
        this.idx = 0;
        this.state = {
            baseType: 1,
            screenGroups: [],
            userList: [],
            screenType: 1,
            fetching: false,
            isDisabled: false
        };
        this.columns = [
            {
                title: '分组名称',
                dataIndex: 'name',
                key: 'name',
                width: 130,
                render: (text, record) => {
                    const {isDisabled} = this.state;
                    return (
                        <div>
                            <Input
                                disabled={isDisabled} value={text}
                                style={(text && text.length > 10) ? {borderColor: 'red'} : null}
                                onChange={this.handleChangeGroup('name', record)}
                            />
                            {
                                (text && text.length > 10) ? (
                                    <p style={{color: 'red', position: 'absolute', fontSize: 12}}>输入超过10字符</p>
                                ) : null
                            }
                        </div>
                    );
                }
            },
            {
                title: '组内成员',
                dataIndex: 'accountIds',
                key: 'accountIds',
                width: 250,
                render: (text, record) => {
                    const {isDisabled, userList} = this.state;
                    return (
                        <Select
                            value={text}
                            mode="multiple" onChange={this.handleChangeGroup('accountIds', record)}
                            // eslint-disable-next-line react/jsx-no-bind
                            getPopupContainer={triggerNode => triggerNode.parentNode}
                            notFoundContent={this.state.fetching ? <Spin size="small" /> : null}
                            showSearch filterOption={false} allowClear
                            onDropdownVisibleChange={this.handleSearch}
                            onSearch={this.handleSearch}
                            labelInValue disabled={isDisabled}
                        >
                            {
                                userList.map(ele => (
                                    <Option value={ele.id} key={ele.id}>
                                        {ele.displayName}
                                    </Option>
                                ))
                            }
                        </Select>
                    );
                }
            },
            {
                title: '目标金额(元)',
                dataIndex: 'targetMoney',
                key: 'targetMoney',
                width: 180,
                render: (text, record) => {
                    const {isDisabled} = this.state;
                    return (
                        <InputNumber
                            value={text} style={{width: 160}}
                            onChange={this.handleChangeGroup('targetMoney', record)}
                        />
                    );
                }
            },
            {
                title: '操作',
                dataIndex: 'operation',
                width: 50,
                render: (text, record) => {
                    const {isDisabled} = this.state;
                    return (
                        <Popconfirm
                            title="确定删除？"
                            // eslint-disable-next-line react/jsx-no-bind
                            onConfirm={this.onDelete.bind(this, record)}
                            okText="是"
                            cancelText="否"
                            disabled={isDisabled}
                        >
                            <Button
                                type="link"
                                data-type="delete"
                                disabled={isDisabled}
                            >
                                删除
                            </Button>
                        </Popconfirm>
                    );
                }
            }
        ];
    }

    componentDidMount() {
        const {match: {params: {id}}} = this.props;
        if (id) {
            this.screenId = parseInt(id, 10);
            // this.getScreenDetail(this.screenId);
        }
        document.body.classList.add('screenList');
    }

    // eslint-disable-next-line
    componentWillReceiveProps(nextProps) {
        const {screenType, detail, match: {params: {id}}} = nextProps;
        const {search} = window.location;
        const copyId = parseInt(search.slice(8), 10) || 0;
        this.setState({
            screenType
        });
        if (!id && !copyId && screenType !== this.props.screenType) {
            this.setState({
                baseType: screenType === 1 ? 1 : 3
            });
        }
        else if ((id || copyId) && JSON.stringify(detail) !== JSON.stringify(this.props.detail)) {
            const {screenType, baseType, screenGroups = [], startTime} = detail;
            const current = moment().locale('zh-cn')
                .format('YYYY-MM-DD HH:mm');
            let isDisabled = false;
            if (startTime) {
                isDisabled = moment(startTime).isBefore(current);
            }
            if (screenType === 2) {
                this.idx = screenGroups.length;
                screenGroups.forEach((ele, index) => {
                    ele.sn = index + 1;
                    ele.targetMoney = ele.targetMoney ? ele.targetMoney / 100 : null;
                    if (ele.accounts && ele.accounts.length) {
                        ele.accountIds = ele.accounts.map(({id, displayName}) => ({key: id, label: displayName}));
                    }
                    else {
                        ele.accountIds = [];
                    }
                    delete ele.accounts;
                });
            }
            this.setState({
                baseType,
                screenGroups,
                isDisabled
            });
        }
    }

    // eslint-disable-next-line class-methods-use-this
    componentWillUnmount() {
        document.body.classList.remove('screenList');
    }

    onDelete = record => {
        this.idx -= 1;
        let {screenGroups: group} = this.state;
        group.splice(record.sn - 1, 1);
        group = group.map((ele, idx) => {
            ele.sn = idx + 1;
            return ele;
        });
        this.setState({
            screenGroups: group
        });
    };

    onSave = () => {
        const {form} = this.props;
        const {baseType, screenGroups, screenType, isDisabled} = this.state;
        form.validateFields((err, values) => {
            if (err) {
                return message.warn('数据不正确');
            }
            if (screenType === 2 && !screenGroups.length) {
                return message.warn('设置分组不可为空');
            }
            if (screenType === 2 && screenGroups.length) {
                if (screenGroups.findIndex(ele => !ele.name || !ele.accountIds.length || !ele.targetMoney) > -1) {
                    return message.warn('设置分组选项均为必填项');
                }
                if (screenGroups.findIndex(ele => ele.name && ele.name.length > 10) > -1) {
                    return message.warn('设置分组名称不可超过10字符');
                }
            }
            const {name, positiveClazzIds, publicClazzIds, time} = values;
            const startTime = moment(time[0]).format('YYYY-MM-DD HH:mm:ss');
            const endTime = moment(time[1]).format('YYYY-MM-DD HH:mm:ss');
            const current = moment().format('YYYY-MM-DD HH:mm:ss');
            const before = moment(startTime).isBefore(current);
            if (before && !isDisabled) {
                return message.warn('统计周期开始时间只能选择当前时间之后');
            }
            const params = {
                name: name.trim(), screenType, baseType, startTime, endTime, bizType: 1,
                positiveClazzIds: positiveClazzIds ? positiveClazzIds.trim() : '',
                publicClazzIds: publicClazzIds ? publicClazzIds.trim() : ''
            };
            if (screenType === 1) {
                let {investmentPrice, groupTotalNum} = values;
                investmentPrice = investmentPrice === null ? null : investmentPrice * 100;
                Object.assign(params, {
                    investmentPrice, orderType: 0,
                });
                if (baseType === 2) {
                    Object.assign(params, {groupTotalNum});
                }
            }
            else {
                const {publicClazzIds, orderType} = values;
                const group = screenGroups.map(({targetMoney, accountIds, ...a}) => ({
                    targetMoney: targetMoney * 100,
                    accountIds: accountIds.map(ele => ele.key),
                    ...a
                }));
                Object.assign(params, {orderType, screenGroups: group});
            }
            if (this.screenId) {
                Object.assign(params, {id: this.screenId});
                this.updateScreen(params);
            }
            else {
                this.createScreen(params);
            }
        });
    };

    createScreen = params => createScreen(params).then(res => {
        if (res) {
            message.success('创建成功');
            this.handlePrevView();
        }
    });

    updateScreen = params => updateScreen(params).then(res => {
        if (res) {
            message.success('更新成功');
            this.handlePrevView();
        }
    });

    handleSearch = e => {
        this.setState({
            userList: [],
            fetching: true
        });
        const keyword = typeof e === 'string' ? e.trim() : '';
        return getAccountList({keyword}).then(res => {
            const {data = []} = res;
            const {screenGroups} = this.state;
            let list = data || [];
            let selectUser = [];
            screenGroups.forEach(ele => {
                selectUser = selectUser.concat(ele.accountIds);
            });
            selectUser = selectUser.map(ele => ele.key);
            list = list.filter(ele => selectUser.findIndex(item =>
                item.toString() === ele.id.toString()) === -1);
            this.setState({
                userList: list,
                fetching: false
            });
        });
    };

    handleBaseType = e => {
        this.setState({
            baseType: e.target.value
        });
    };

    handlePrevView = () => {
        this.props.history.push(`/manage/screen/list/${PAGE_ENUM.BIG_SCREEN_CONFIG}`);
    };

    handleAddScreenGroup = () => {
        this.idx += 1;
        const {screenGroups: group} = this.state;
        const value = {name: null, accountIds: [], targetMoney: null, sn: this.idx};
        this.setState({
            screenGroups: [...group, value]
        });
    };

    handleChangeGroup = (type, record) => e => {
        const index = record.sn - 1;
        let value = null;
        const {screenGroups: group} = this.state;
        if (type === 'name') {
            value = e.target.value.trim();
            if (value.length > 10) {
                // message.warn('分组名称不可超过10个字符');
            }
        }
        else {
            value = e;
        }
        group[index][type] = value;
        this.setState({
            screenGroups: group
        });
    };

    render() {
        const {baseType, screenGroups, screenType, isDisabled} = this.state;
        const {form, detail} = this.props;
        const {getFieldDecorator} = form;
        return (
            <Fragment>
                <Form.Item label="大屏名称">
                    {getFieldDecorator('name', {
                        initialValue: detail && detail.name || '',
                        rules: [
                            {required: true, message: '该选项为必填项'},
                            {max: 30, message: '输入不可超过30字符'},
                            {whitespace: true, message: '输入内容不可为空格'}
                        ]
                    })(
                        <Input placeholder="最多填写30字符" style={{width: 300}} disabled={isDisabled} />
                    )}
                </Form.Item>
                <Form.Item label="正价课班级ID">
                    {getFieldDecorator('positiveClazzIds', {
                        initialValue: detail && detail.positiveClazzIds || '',
                        rules: [
                            {required: true, message: '该选项为必填项'},
                            {whitespace: true, message: '输入内容不可为空格'}
                        ]
                    })(
                        <TextArea
                            rows={3} placeholder="多个班级用‘，’隔开，不区分中英文逗号"
                            style={{width: 300}} disabled={isDisabled}
                        />
                    )}
                </Form.Item>
                <Form.Item label="统计周期">
                    {getFieldDecorator('time', {
                        initialValue: detail && [moment(detail.startTime), moment(detail.endTime)]
                            || [moment().add(1, 'H'), moment().add(97, 'H')],
                        rules: [{required: true, message: '该选项为必填项'}]
                    })(
                        <RangePicker
                            showTime={{format: 'HH:mm'}}
                            format="YYYY-MM-DD HH:mm"
                            disabled={isDisabled}
                        />
                    )}
                </Form.Item>
                {
                    screenType === 1 && (
                        <Form.Item label="转化基数">
                            {getFieldDecorator('baseType1', {
                                initialValue: detail && detail.baseType || 1,
                                rules: [{required: true, message: '该选项为必填项'}]
                            })(
                                <Radio.Group onChange={this.handleBaseType} disabled={isDisabled}>
                                    <Radio value={1}>以免费课/低价课的总报名人数为准</Radio>
                                    <Radio value={2}>以公开课群总人数为准</Radio>
                                </Radio.Group>,
                            )}
                        </Form.Item>
                    )
                }
                {
                    screenType === 2 && (
                        <Form.Item label="业绩归属方式">
                            {getFieldDecorator('baseType2', {
                                initialValue: detail && detail.baseType || 3,
                                rules: [{required: true, message: '该选项为必填项'}]
                            })(
                                <Radio.Group onChange={this.handleBaseType} disabled={isDisabled}>
                                    <Radio value={3}>原课程辅导班的销售为业绩归属人</Radio>
                                    <Radio value={4}>原课程辅导班的辅导老师为业绩归属人</Radio>
                                    <Radio value={5}>特殊链接记录的辅导老师为业绩归属人</Radio>
                                    <Radio value={6}>特殊链接记录的销售为业绩归属人</Radio>
                                    <Radio value={7}>目标课辅导老师为业绩归属人</Radio>
                                </Radio.Group>,
                            )}
                        </Form.Item>
                    )
                }
                {
                    screenType === 1 ? baseType === 1 ? (
                        <Form.Item label="免费课/低价课班级ID">
                            {getFieldDecorator('publicClazzIds', {
                                initialValue: detail && detail.publicClazzIds || '',
                                rules: [
                                    {required: true, message: '该选项为必填项'},
                                    {whitespace: true, message: '输入内容不可为空格'}
                                ]
                            })(
                                <TextArea
                                    rows={3} placeholder="多个班级用‘，’隔开，不区分中英文逗号"
                                    style={{width: 300}} disabled={isDisabled}
                                />
                            )}
                        </Form.Item>
                    ) : (
                        <Form.Item label="群人数">
                            {getFieldDecorator('groupTotalNum', {
                                initialValue: detail && detail.groupTotalNum || null,
                                rules: [
                                    {required: true, message: '该选项为必填项'},
                                    {pattern: /^\+?[1-9]\d*$/, message: '需要大于0的正整数'}
                                ]
                            })(
                                <InputNumber
                                    precision={0}
                                    placeholder="请输入数值"
                                    style={{width: 300}}
                                />
                            )}
                        </Form.Item>
                    ) : (baseType === 3 || baseType === 4) && (
                        <Form.Item label="原班级ID">
                            {getFieldDecorator('publicClazzIds', {
                                initialValue: detail && detail.publicClazzIds || '',
                                rules: [
                                    {
                                        required: true,
                                        message: '该选项为必填项'
                                    },
                                    {whitespace: true, message: '输入内容不可为空格'}
                                ]
                            })(
                                <TextArea
                                    rows={3} style={{width: 300}} disabled={isDisabled}
                                    placeholder="多个班级用‘，’隔开，不区分中英文逗号；如果不选择原课程辅导班的辅导老师/销售为业绩归属人，则非必填"
                                />
                            )}
                        </Form.Item>
                    )
                }
                {
                    screenType === 1 && (
                        <Form.Item label="投放成本(元)">
                            {getFieldDecorator('investmentPrice', {
                                initialValue: detail && (detail.investmentPrice / 100) || null,
                                rules: [{pattern: /^0(?=\.)|^[1-9]+/, message: '需要大于0'}]
                            })(
                                <InputNumber
                                    placeholder="请输入数值" style={{width: 300}}
                                />
                            )}
                        </Form.Item>
                    )
                }
                {
                    screenType === 2 && (
                        <Form.Item label={(
                            <span>
                                <span style={{color: 'red'}}>*</span>
                                设置分组
                            </span>
                        )}
                        >
                            {getFieldDecorator('screenGroups', {
                            })(
                                <Fragment>
                                    <p>
                                        <span style={{marginRight: 20}}>大屏最多展示top10分组</span>
                                        <Button
                                            type="dashed" onClick={this.handleAddScreenGroup}
                                            disabled={isDisabled}
                                        >
                                            添加分组
                                        </Button>
                                    </p>
                                    <DataDetail
                                        rowKey="sn" pagination={false} isLoading={false}
                                        dataSource={screenGroups} columns={this.columns}
                                    />
                                </Fragment>
                            )}
                        </Form.Item>
                    )
                }
                {
                    screenType === 2 && (
                        <Form.Item label="组排序方式">
                            {getFieldDecorator('orderType', {
                                initialValue: detail && detail.orderType || 1,
                                rules: [{required: true, message: '该选项为必填项'}]
                            })(
                                <Radio.Group>
                                    <Radio value={1}>按完成率倒序</Radio>
                                    <Radio value={2}>按金额倒序</Radio>
                                </Radio.Group>,
                            )}
                        </Form.Item>
                    )
                }
                <div className="footer-container">
                    <Button type="primary" className="cancel" onClick={this.handlePrevView}>取消</Button>
                    <Button type="primary" onClick={this.onSave}>保存</Button>
                </div>
            </Fragment>
        );
    }
}

export default Form.create()(withRouter(MoneyScreenConfig));
